import axios, {AxiosInstance, AxiosError, AxiosResponse, AxiosRequestConfig} from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();

const service:AxiosInstance = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 5000
});

//统一处理请求操作
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        const token = localStorage.getItem("token");
        if(token!=null){
            config.headers={
                "Authorization" : token 
            }
        }
        return config;
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject();
    }
);

//返回的统一处理
service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200) {
           
            if(response.data.code === 200){
                //直接返回response
                //如果头部中有新的token，那么则更新本地的存储的token
                const refreshToken= response.headers["Authorization"];
                if(refreshToken!=null && refreshToken!=""){
                    //保存新的refreshtoken
                    localStorage.setItem("token",refreshToken)
                }

                return response;
            }else if(response.data.code === 401){
                alert(response.data.msg)
                localStorage.clear();
                window.location.href ="/";
            }else{
                ElMessage.error(response.data.msg)
                //reject();
                return Promise.reject();
            }
          
        } else {
            if(response.data.code === 401){
                ElMessage.error(response.data.msg)
                router.push({
                    path:"/login"
                })
            } 
           return Promise.reject();
        }
    },
    (error: AxiosError) => {
        return Promise.reject();
    }
);

export default service;
